package com.nebula.api.modules.member.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.nebula.api.common.entity.TokenUser;
import com.nebula.api.modules.member.entity.CmfMember;
import com.nebula.api.modules.member.entity.LoginQo;
import com.nebula.api.modules.member.mapper.CmfMemberMapper;
import com.nebula.api.modules.member.service.ICmfMemberService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nebula.api.utils.RedisUtils;
import com.nebula.commons.redis.RedisKeys;
import link.ahsj.core.utils.base.AppAssertUtil;
import lombok.val;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;

/**
 * <p>
 * 用户会员表 积分商城用户 服务实现类
 * </p>
 *
 * @author ChanlunLee
 * @since 2022-10-10
 */
@Service
public class CmfMemberServiceImpl extends ServiceImpl<CmfMemberMapper, CmfMember> implements ICmfMemberService {

    @Autowired
    private CmfMemberMapper cmfMemberMapper;

    @Autowired
    private RedisUtils redisUtils;

    @Override
    public String login(LoginQo loginQo) {
        //在service层调用mapper层的方法
//        cmfMemberMapper.selectOne(条件构造器)
        //创建条件构造器
        LambdaQueryWrapper<CmfMember> warpper = new LambdaQueryWrapper<>();
        //条件
        //查询用户名和密码是否在数据库中存在
        warpper.eq(CmfMember::getUsername, loginQo.getUsername()).eq(CmfMember::getPassword, loginQo.getPassword());
        CmfMember cmfMember = cmfMemberMapper.selectOne(warpper);

        //判断cmfMember是否为null
        AppAssertUtil.isNull(cmfMember, "用户不存在");
        //判断密码是否正确
        AppAssertUtil.isErr(!loginQo.getPassword().equals(cmfMember.getPassword()), "密码错误");

        //返回token
//        1,生成token
        String token = IdWorker.get32UUID();
        //创建TokenUser对象
        TokenUser tokenUser = new TokenUser();
        System.out.println("cmfMember" + cmfMember);
        //把cmfMember设置到tokenUser里面
        tokenUser.setUserInfo(cmfMember);
        System.out.println("tokenUser:" + tokenUser);

//        2,把用户的信息存储到redis里
//        redis.set(key,val)
        //使用工具类拼接token
        redisUtils.set(RedisKeys.getAppToken(token), tokenUser);
        return token;
    }

//    获取用户信息
@Override
public HashMap<Object, Object> userProfiles(CmfMember cmfMember) {
//        通过id获取用户信息
    CmfMember men = this.getById(cmfMember.getId());
//        非空判断
    AppAssertUtil.isNull(men, "用户不存在");

//        创建HashMap对象
    HashMap<Object, Object> userProfilesHashMap = new HashMap<>();

//        put(key,val):往userProfilesHashMap对象存储一个key：userInfo，对应的值men
    userProfilesHashMap.put("userInfo", men);

//        返回HashMap对象
    return userProfilesHashMap;

}
}
